const https = require('https');

const SQLHelper = require('./SQLHelper')
///雪花算法生成id
const snowflake = require('./snowflake')
const {formatTime} = require('./util');
const { title } = require('process');
const { NULL } = require('mysql/lib/protocol/constants/types');
const multer = require('multer')
const storage = multer.diskStorage({
    destination:'./uploads',//保存的路径
    filename:function(req,file,cd){
        ///获取图片类型
        let fileType = file.originalname.split('.')
        fileType = fileType[fileType.length - 1]
        cd(null,snowflake() + '.' +fileType)
    }
})
const upload = multer({storage:storage})

module.exports = function(app){
    ///登录拦截中间件 判断请求是否携带 token 如果没有 一下接口均不能使用 
    function loginRouter(req,res,next){
        let token = req.headers.token
        if(token){
            SQLHelper(`select * from session where id = ${token}`).then(ret => {
                if(ret.length){
                    let session = ret[0]
                    req.session = {
                        userId:session.userId,
                        userName:session.userName
                    }
                    next()
                }else{
                    res.status(406).send({errorMsg:'当前用户未登录'})
                }
            })
        }else{
            res.status(405).send({errorMsg:'缺少token，请先进行登录'})
        }
    }
    ///让初登陆以为的所有小程序接口都先验证登陆
    app.use('/wx',loginRouter)

    //文件上传
    app.post('/upload',upload.single('file'),(req,res)=>{
        res.send(req.file)
    })

    ///微信登录
    app.get('/wxlogin', (req, res,next) => {
        let code = req.query.code
        let appid="wx9cb653bd83faa8a7"
        let secret='1606fbc0bea73e57711b342fd3d89dc7'
        https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
            ret.on('data', (ret) => {
                ret = JSON.parse(ret.toString())
                let openid = ret.openid
                if(!openid){
                    res.send({errorMsg: ret.errMsg || '获取openid错误'})
                }else{
                    ///查询用户是否已经注册
                    let queryMember = `select * from member where openId = '${openid}'`
                    SQLHelper(queryMember).then(membersRet => {
                        if(membersRet.length){///用户已经存在
                            ///挂载到req
                            req.member = membersRet[0]
                            next()
                        }else{///用户不存在,使用openid注册用户
                            SQLHelper(`INSERT INTO member(openId) VALUES('${openid}')`).then(newMember => {
                                ///注册成功返回新用户信息
                                SQLHelper(queryMember).then(newMember => {
                                    ///挂载到req
                                    req.member = newMember[0]
                                    next()
                                })
                            })
                        }
                    })
                }
            });

        }).on('error', (e) => {
            console.error(e)
            res.send({errorMsg:'获取openid错误'})
        });
    },(req,res) => {
        let member = req.member
        let token = snowflake()
        ///缓存token到session表
        SQLHelper(`
        INSERT INTO session(id,userId,userName,inTime,platform) 
        VALUES(${token},'${member._id}','${member.nickName}','${formatTime(new Date())}','wx')
        `).then(ret => {
            res.send({
                nickName:member.nickName,
                token,
                openId:member.openId,
                avatarUrl:member.avatarUrl,
                _id:member._id
            })
        })
    })
    ///修改用户信息
    app.put('/wx/member',(req,res) => {
        
        let userInfo = req.body
        SQLHelper(`
        update member 
        set nickName = '${userInfo.nickName}',avatarUrl = '${userInfo.avatarUrl}'
        where _id = ${req.session.userId}
        `).then(ret => {
            res.send("用户数据缓存数据成功")
        })
    })

    ///获取首页轮播图和分类同一接口
    //type必填 这个区分是轮播图 还是分类区
    app.get('/banner_category',(req,res) => {
        if(req.query.type == 'banner'){
            if(req.query.num <= 1 ||req.query.num >6 || req.query.num == 'undefined'){
                req.query.num = 6  //如果前台没有传入 限制的条数 ，则默认轮播图数量为6且至少为2条
            }
        }
        if(req.query.type == 'category'){
            if(req.query.num == 'undefined'){
                req.query.num = 8  //利于页面美观 分类区八条数据
            }
        }
        SQLHelper(`select * from banner_category where type='${req.query.type}' and state = 1 and status limit ${req.query.num}`).then(ret =>{
            res.send(ret)
        })
    })

    //获取首页新闻数据列表
    app.get('/news',(req,res) =>{
        if(req.query.num == 'undefined'){
            req.query.num = 4  //默认四条数据 
        }
        SQLHelper(`select * from news where state = 1 and status = 1 limit ${req.query.num}`).then(ret =>{
            res.send(ret)
        })
    })

    //获取帖子数据列表
    app.get('/wx/posts1',(req,res) =>{
        let type = req.query.type
        let whereSql = 'from posts1 where state = 1'
        if(type != 'undefined') whereSql += ` and shool like "%${type}%" `
        SQLHelper(`select * ${whereSql}  order by data desc`).then(ret=>{
            for(let i = 0;i<ret.length;i++){
                if(ret[i].imgs){
                    let arry=[]
                    arry = ret[i].imgs.split(";")
                    ret[i].imgs = arry
                }
                if(ret[i].hotFrom){
                    let arry1=[]
                    arry1 = ret[i].hotFrom.split(";")
                    ret[i].hotFrom = arry1
                }
            }
            res.send(ret)
        })
    })
    //获取关注的人
    app.get('/wx/lovePosts',(req,res) =>{
        const loves = JSON.parse(req.query.loves)
        whereSql=''
        for(let i = 0;i<loves.length;i++){
            whereSql += `SELECT * FROM posts1 WHERE userName="${loves[i]}" AND state =1 order by data desc;`
        }
        SQLHelper(`${whereSql} `).then(ret=>{
            const arry=[] //占存关注的人的帖子
           
            for(let y = 0;y<ret.length;y++){
                for(let j =0;j<ret[y].length;j++){
                    if(ret[y][j].imgs){
                        let arry=[]
                        arry = ret[y][j].imgs.split(";")
                        ret[y][j].imgs = arry
                    }
                    if(ret[y][j].hotFrom){
                        let arry1=[]
                        arry1 = ret[y][j].hotFrom.split(";")
                        ret[y][j].hotFrom = arry1
                    }
                    arry.push(ret[y][j])
                }
            }
            res.send(arry)
        })
    })
    
    //获取评论数据
    app.get('/wx/comment',(req,res)=>{
        if(req.query.type){
            SQLHelper(`SELECT * FROM comment WHERE state = 1 and userfromId = '${req.query.type}'`).then(ret=>{
                res.send(ret)
            })
        }else{
            req.send({errMsg:"传入数据错误"})
        }
    })

    //这里新增评论
    app.post('/wx/comment',(req,res) => {
        let userfromId = req.body.userfromId,name = req.body.name,data = req.body.data,shool = req.body.shool,touxaing = req.body.touxaing,neirong = req.body.neirong
        let dianzan = req.body.dianzan 
        //req.body.userfromId,req.body._id必填
        if(userfromId){
            SQLHelper(`
            INSERT INTO comment(userfromId,name,data,shool,touxaing,neirong,dianzan,state) 
            VALUES('${userfromId}','${name}','${data}','${shool}','${touxaing}','${neirong}','${dianzan}',1)
            `).then(ret => {
                res.send({success:true})
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })

    //新增帖子
    app.post('/wx/edit',(req,res) => {
        let userId = snowflake(),userName = req.body.userName,data = req.body.data,shool = req.body.shool,title = req.body.title,imgs = req.body.imgs
        let dianzan = req.body.dianzan,score = req.body.score,hotFrom=req.body.hotFrom,headPortrait=req.body.headPortrait,specialimg = req.body.specialimg
        //userId必填
        if(userId){
            SQLHelper(`
            INSERT INTO posts1(userId,userName,data,shool,title,imgs,dianzan,state,score,hotFrom,specialimg,headPortrait) 
            VALUES('${userId}','${userName}','${data}','${shool}','${title}','${imgs}','${dianzan}',1,'${score}','${hotFrom}','${specialimg}','${headPortrait}')
            `).then(ret => {
                res.send({success:true})
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })
    //点赞功能帖子区
    app.put('/wx/posts1',(req,res) => {
        let userInfo = req.body
        SQLHelper(`
        update posts1
        set diazanstate = '1',dianzan = '${userInfo.dianzan+1}'
        where userId = '${userInfo.userId}'
        `).then(ret => {
            res.send("点赞成功")
        })
    })
    //点赞功能评论区
    app.put('/wx/comment',(req,res) => {
        console.log(req.body)
        let userInfo = req.body
        SQLHelper(`
        update comment
        set dianzanstate = '1',dianzan = '${userInfo.dianzan+1}'
        where _id = '${userInfo._id}'
        `).then(ret => {
            res.send("点赞成功")
        })
    })
    
    ///获取收获详情
    ///addressId 地址_id 必填
    app.get('/wx/address/detail',(req,res) => {
        if(req.query.addressId){
            SQLHelper(`
            select * from address where _id = ${req.query.addressId}
            `).then(ret => {
                res.send(ret.length ? ret[0] : {errorMsg:'未获取到地址详情'})
            })
        }else{
            res.send({errorMsg:'请传入addressId'})
        }
    })

    ///新增收货地址
    ///memberId 用户ID 必填
    ///receiver 收货人 必填
    ///phone 手机号 必填
    ///city 省市区 必填
    ///area 详细地址 非必填
    app.post('/wx/address',(req,res) => {
        if(req.body.receiver &&  req.body.phone && req.body.city){
            SQLHelper(`
            INSERT INTO address(state,memberId,receiver,phone,city,area) 
            VALUES(1,'${req.session.userId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || ''}')
            `).then(ret => {
                res.send(ret)
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })

    ///修改收货地址
    ///addressId 地址_id 必填
    ///receiver 收货人 非必填
    ///phone 手机号 非必填
    ///city 省市区 非必填
    ///area 详细地址 非必填
    app.put('/wx/address',(req,res) => {
        if(req.body.addressId){
            ///需要修改的项
            let updateKey = ['receiver','phone','city','area']
            let updateValues = []
            for(let i = 0; i < updateKey.length; i ++){
                let key = updateKey[i],value = req.body[key]
                if(value) updateValues.push(`${key}='${value}'`)///判断哪些项需要修改
            }
            SQLHelper(`UPDATE address set ${updateValues.join(',')} WHERE _id = ${req.body.addressId}`).then(ret => {
                res.send(ret)
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })

    ///修改为默认地址
    ///addressId 主码_id 必填
    ///memberId 用户_id 必填
    ///isDefault 是否默认 非必填
    app.put('/wx/address/default',(req,res) => {
        let addressId = req.body.addressId,memberId = req.session.userId,isDefault = req.body.isDefault == 1 ? 1 : 0
        if(addressId && memberId){
            if(isDefault == 1){///设置默认地址
                ///取消其他默认地址
                SQLHelper(`
                UPDATE address 
                set isDefault = 0 
                WHERE isDefault = 1 AND memberId = ${memberId}
                `).then(ret => {
                    SQLHelper(`
                    UPDATE address 
                    set isDefault = 1 
                    WHERE _id = ${addressId}
                    `).then(ret => {
                        res.send(ret)
                    })
                })
            }else{///取消默认地址
                SQLHelper(`
                UPDATE address 
                set isDefault = 0 
                WHERE _id = ${addressId}
                `).then(ret => {
                    res.send(ret)
                })
            }
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })


    ///删除地址 逻辑删除
    ///addressId 主码_id 必填
    app.delete('/wx/address',(req,res) => {
        let addressId = req.body.addressId
        if(addressId){
            SQLHelper(`
            UPDATE address 
            set state = 0 
            WHERE _id = ${addressId}
            `).then(ret => {
                res.send(ret)
            })
        }else{
            res.send({errorMsg:'传入参数错误'})
        }
    })

}